require "Logic/Config"
require "Battle/Entity/Entity"

FightEntity = Entity:new();
FightEntity.__index = FightEntity;

function FightEntity:new(roleInfo, is)
    local object = Entity:new(roleInfo, is);
    setmetatable(object, FightEntity);
    return object;
end

function FightEntity:setShield(num, max)
    if self.shield ~= 0 then
        local damageResult = {};
        damageResult.damage = self.shield - num;
        damageResult.type = Config.damageType.shields;
        if num ~= 0 and max ~= 0 then
            showFightDamage(damageResult, self.roleObj, self);
        end
    end
    self.shield = tonumber(num);
    self.shieldMax = tonumber(max);
    --self.shieldNum = tonumber(value);
    if num == 0 then
        self.shield = 0;
        self.shieldMax = 0;
    end

    self:setHP(self.hp, self.maxHP);
end

function FightEntity:setHP(hp, max)
    if self.isDead or self.isDeading then
        return ;
    end
    self.hp = math.max(tonumber(hp),0);
    self.hp = math.min(self.hp,max);
    local max_hp = 0;
    local hpPercent = 100;
    local shieldPercent = 0;
    if self.shield > 0 and self.hp > 0 then
        if self.shield <= max - self.hp then
            shieldPercent = (self.shield + hp) / max;
            hpPercent = self.hp / max;
        else
            max_hp = self.hp + self.shield;
            shieldPercent = 1;
            hpPercent = self.hp / max_hp;
        end


    else
        max_hp = max;
        hpPercent = self.hp / max_hp;
    end
    if not self.isBloodBar then
        return;
    end
    local hpNew = hpPercent * 100;
    if self.headBar ~= nil then
        self.hpSlider.value = hpPercent * 100;
        if self.hpSlider.value == 100 then
            self.hp3Slider.value = 100;
        end
    end
    if self.hp2Slider ~= nil then
        self.hp2Slider.value = shieldPercent * 100;
    end

    if self.headBar then
        --self.headBar.visible = true;
    end
    if self.hpTimer == nil then
        self.hpTimer = Timer.New(function()
            if self.headBar ~= nil then
            end
        end, self.hideHPTime, 1);
    else
        self.hpTimer:Reset(function()
            if self.headBar ~= nil then
            end
        end, self.hideHPTime, 1);
    end
    self.hpTimer:Start();
    if shieldPercent ~= 1 then
        if self.hp3Slider ~= nil and self.hp3Slider.value > hpNew then
            local delta = self.hp3Slider.value - hpNew;
            if self.hp3Timer == nil then
                self.hp3Timer = Timer.New(function()
                    self.hp3Slider.value = self.hp3Slider.value - (delta / 20);
                end, self.BloodTime / 20, 20);
            else
                self.hp3Timer:Reset(function()
                    self.hp3Slider.value = self.hp3Slider.value - (delta / 20);
                end, self.BloodTime / 20, 20);
            end
            self.hp3Timer:Start();
        end
    else
        self.hp3Slider.value = hpNew;
    end
end
